package com.huynhchihieu.springsecurity.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.huynhchihieu.domain.Domainuser;
import com.huynhchihieu.service.UserService;
import com.huynhchihieu.springsecurity.dto.ExampleUserDetails;

/**
 * This class loads the requested user by using a Spring Data JPA repository.
 * @author Petri Kainulainen
 */
@Service(value="repositoryUserDetailsService")
@Transactional
public class RepositoryUserDetailsService implements UserDetailsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(RepositoryUserDetailsService.class);

    @Autowired
    private UserService userService;

    
    

//    @Autowired
//    UserConnectionRepository userConnectionRepository;

    /**
     * Loads the user information.
     * @param username  The username of the requested user.
     * @return  The information of the user.
     * @throws UsernameNotFoundException    Thrown if no user is found with the given username.
     */
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LOGGER.debug("Loading user by username: {}", username);

        Domainuser user = userService.getUserByEmail(username);
        LOGGER.debug("Found user: {}", user);

        if (user == null) {
            throw new UsernameNotFoundException("No user found with username: " + username);
        }

        String socialImageUrl = null;
//        if(user.getSignInProvider() != null){
//        	UserConnection userConnection = userConnectionRepository.findByUserId(username);
//        	socialImageUrl = userConnection.getSocialUserImageURL();
//        }
        ExampleUserDetails principal = ExampleUserDetails.getBuilder()
                .firstName(user.getFirstname())
                .id((long) user.getUserId())
                .lastName(user.getLastname())
                .password(user.getPassword())
                .role(user.getRole())
                .socialSignInProvider(user.getSignInProvider())
                .username(user.getEmail())
                .socialUserImageUrl(socialImageUrl != null ? socialImageUrl : "")
                .build();

        LOGGER.debug("Returning user details: {}", principal);

        return principal;
    }
}
